package roughTimeNow

import (
	"gitee.com/kingzyt/common/util"
	"sync"
	"time"
)

type RoughTimeNow struct {
	checkInterval time.Duration
	mutex         sync.RWMutex

	now    time.Time
	nowS   int64
	nowNS  int64
	nowStr string
	nowYMD string
}

func NewRoughTimeNow(checkInterval time.Duration) *RoughTimeNow {
	rlt := &RoughTimeNow{checkInterval: checkInterval}
	rlt.refreshNowData()
	go rlt.update()
	return rlt
}

func (self *RoughTimeNow) refreshNowData() {
	self.now = time.Now()
	self.nowS = self.now.Unix()
	self.nowNS = self.now.UnixNano()
	self.nowStr = self.now.Format(time.RFC3339)
	self.nowYMD = util.TimeStringYMD(self.now)
}

func (self *RoughTimeNow) Now() time.Time {
	self.mutex.RLock()
	defer self.mutex.RUnlock()

	return self.now
}
func (self *RoughTimeNow) NowS() int64 {
	self.mutex.RLock()
	defer self.mutex.RUnlock()

	return self.nowS
}
func (self *RoughTimeNow) NowNS() int64 {
	self.mutex.RLock()
	defer self.mutex.RUnlock()

	return self.nowNS
}
func (self *RoughTimeNow) NowStr() string {
	self.mutex.RLock()
	defer self.mutex.RUnlock()

	return self.nowStr
}
func (self *RoughTimeNow) NowYMD() string {
	self.mutex.RLock()
	defer self.mutex.RUnlock()

	return self.nowYMD
}
func (self *RoughTimeNow) update() {
	util.UpdateProc(self.checkInterval, false, func() (ok bool) {
		self.mutex.Lock()
		defer self.mutex.Unlock()
		self.refreshNowData()
		return true
	})
}
